package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.AdminIdAndRoleIdMapper;
import com.qingcheng.dao.AdminMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.pojo.system.AdminAndRoleId;
import com.qingcheng.pojo.system.AdminIdAndRoleId;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.util.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = AdminService.class)
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminIdAndRoleIdMapper adminIdAndRoleIdMapper;

    /**
     * 返回全部记录
     * @return
     */
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Admin> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectAll();
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Admin> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return adminMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Admin> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectByExample(example);
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Admin findById(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param admin
     */
   /* public void add(Admin admin) {
        adminMapper.insert(admin);
    }*/

    /**
     * 修改
     * @param admin
     */
    /*public void update(Admin admin) {
        adminMapper.updateByPrimaryKeySelective(admin);
    }*/

    /**
     *  删除
     * @param id
     */
    public void delete(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Admin findByName(String name) {
        Admin admin = new Admin();
        admin.setLoginName(name);
        Admin admin1 = adminMapper.selectOne(admin);
        return admin1;
    }

    @Override
    public void updatePassword(String name, Map<String, String> passwordMap) {
        Admin admin = findByName(name);

        if (passwordMap.size() == 0 || passwordMap.size() < 3){//判断信息是否合法
            throw new RuntimeException("输入错误,请重新输入!");
        }
        if (!BCrypt.checkpw(passwordMap.get("oldPassword"),admin.getPassword())){//验证旧密码
            throw new RuntimeException("原密码错误!");
        }
        if (!passwordMap.get("newPassword").equals(passwordMap.get("againPassword"))){
            throw new RuntimeException("两次密码不一致!");
        }

        //生成新加密密码
        String gensalt = BCrypt.gensalt();
        String newPassword = BCrypt.hashpw(passwordMap.get("newPassword"), gensalt);
        admin.setPassword(newPassword);
        //更新
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     * 新增admin和roles
     * @param map
     */
    @Override
    @Transactional
    public void add(Map<String, Object> map) {
        Admin admin = new Admin();
        admin.setLoginName((String) map.get("loginName"));
        String password = (String) map.get("pass");
        //生成加密密码
        String gensalt = BCrypt.gensalt();
        String newPassword = BCrypt.hashpw(password, gensalt);
        admin.setPassword(newPassword);

        admin.setStatus("1");
        //插入一个新管理员
        adminMapper.insertSelective(admin);

        Integer adminId = admin.getId();

        //更新tb_admin_role表
        AdminIdAndRoleId adminIdAndRoleId = new AdminIdAndRoleId();
        adminIdAndRoleId.setAdminId(adminId);
        List<Integer> listRoles = (List<Integer>) map.get("selectedRoles");
        for (Integer roleId : listRoles) {
            adminIdAndRoleId.setRoleId(roleId);
            adminIdAndRoleIdMapper.insert(adminIdAndRoleId);
        }

    }

    /**
     * 修改admin和roleIds
     * @param map
     */
    @Override
    @Transactional
    public void update(Map<String, Object> map,Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        admin.setLoginName((String) map.get("loginName"));

        //修改,密码可以为空
        if (map.get("pass") != null){
            String password = (String) map.get("pass");
            //生成加密密码
            String gensalt = BCrypt.gensalt();
            String newPassword = BCrypt.hashpw(password, gensalt);
            admin.setPassword(newPassword);
        }
        admin.setStatus("1");
        //更新一个管理员
        adminMapper.updateByPrimaryKeySelective(admin);

        //先把tb_admin_role表删除,再添加

        Example example = new Example(AdminIdAndRoleId.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId",id);
        adminIdAndRoleIdMapper.deleteByExample(example);

        //添加
        AdminIdAndRoleId adminIdAndRoleId = new AdminIdAndRoleId();
        adminIdAndRoleId.setAdminId(id);
        List<Integer> listRoles = (List<Integer>) map.get("selectedRoles");
        for (Integer roleId : listRoles) {
            adminIdAndRoleId.setRoleId(roleId);
            adminIdAndRoleIdMapper.insert(adminIdAndRoleId);
        }


    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 用户名
            if(searchMap.get("loginName")!=null && !"".equals(searchMap.get("loginName"))){
                //criteria.andLike("loginName","%"+searchMap.get("loginName")+"%");
                criteria.andEqualTo("loginName",searchMap.get("loginName"));
            }
            // 密码
            if(searchMap.get("password")!=null && !"".equals(searchMap.get("password"))){
                criteria.andLike("password","%"+searchMap.get("password")+"%");
            }
            // 状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                //criteria.andLike("status","%"+searchMap.get("status")+"%");
                criteria.andEqualTo("status",searchMap.get("status"));
            }

            // id
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }

        }
        return example;
    }

}
